package com.ciwong.epaper.modules.wordlist;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.wordlist.bean.PageListBean;
import com.ciwong.epaper.util.WordUtil;
import com.ciwong.epaper.widget.ColorationTextView;
import com.ciwong.epaper.widget.evaluate.SpeechTextView;
import com.ciwong.epaper.widget.evaluate.UnitSpeechView;
import com.ciwong.epaper.widget.evaluate.WorkViewPager;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.DeviceUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by young  on 2018/4/2.
 */
public class WordSpeechView extends BaseWordFrameLayot implements ViewPager.OnPageChangeListener {
    private WorkViewPager viewPager;
    private LayoutInflater inflater;
    private int defaultWordColor;
    private int scoreDefColor;// 评分结果颜色
    private TextView scoreView;
    private int currentPageIndex;

    private List<PageListBean> words;
    private List<Sentence> wordDatas;
    private UnitSpeechView.OnPageSelectChangeListener mSelelectChangeListener;
    private static final String TAG = "WordSpeechView";

    public WordSpeechView(Context context) {
        super(context);
        init();
    }

    public WordSpeechView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public WordSpeechView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        viewPager = new WorkViewPager(getContext());
        addView(viewPager);
        viewPager.setLayoutParams(
                new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
        inflater = LayoutInflater.from(getContext());
        viewPager.setCanScroll(false);
        viewPager.setVerticalScrollBarEnabled(false);
        viewPager.setHorizontalScrollBarEnabled(false);
        viewPager.setOnPageChangeListener(this);
        defaultWordColor = getContext().getResources()
                .getColor(R.color.default_text_color);
        scoreDefColor = 0xff999999;

    }

    /**
     * 是否可以滚动
     *
     * @param canScroll
     */
    public void setCanScroll(boolean canScroll) {
        viewPager.setCanScroll(canScroll);
    }

    /**
     * 设置显示数据源
     *
     * @param words
     * @param
     * @param scoreView
     * @param userId
     * @param currPage
     */
    public void setData(List<PageListBean> words, WordListBottomView wordBottomView,
                        TextView scoreView, long userId, int currPage) {
        initData(wordBottomView, userId);
        this.scoreView = scoreView;
        this.words = words;
        int len = words == null ? 0 : words.size();
        wordDatas = new ArrayList<Sentence>();
        for (int i = 0; i < len; i++) {
            PageListBean word = words.get(i);
            String wStr = word.getContent();
            String[] arr = SpeechUtils.replaceAsSpace(wStr).split(" ");
            List<WordDetail> ws = new ArrayList<WordDetail>();
            Sentence sentence = new Sentence();

            for (String str : arr) {
                WordDetail w = new WordDetail();
                w.setPretations(word.getResource().getPretatuins());
                if (word.getResource().getSentences() != null && word.getResource().getSentences().size() > 0) {
                    w.setSentences(word.getResource().getSentences().get(0).getText());
                }
                w.setText(str);
                // w.setSyllable();
                w.setSymbol(word.getResource().getSymbol());
                w.setwId(word.getWordId());
                w.setWordFile(word.getResource().getAudioUrl());
                sentence.setSentenceMp3(w.getWordFile());
                w.setWordPic(word.getResource().getPicture_url());
                //w.setWordType(word.getWordType());
                w.setColor(defaultWordColor);
                ws.add(w);
            }

            sentence.setWordDetails(ws);
            sentence.setText(wStr);
            wordDatas.add(sentence);
        }
        WordSpeechView.ViewPageAdapter adapter = new WordSpeechView.ViewPageAdapter();
        viewPager.setAdapter(adapter);
        currentPageIndex = currPage;
        viewPager.setCurrentItem(currPage);
    }


    private int pageSize() {
        return wordDatas == null ? 0 : wordDatas.size();
    }

    /**
     * 下一页
     */
    public void next() {
        currentPageIndex++;
        if (currentPageIndex >= pageSize()) {
            currentPageIndex = pageSize() - 1;
            return;
        }
        animTo(currentPageIndex);
    }

    /**
     * 滚动到指定界面
     *
     * @param index 索引
     */
    public void animTo(int index) {
        currentPageIndex = index;
        viewPager.setCurrentItem(index, true);
    }

    /**
     * 显示指定界面
     *
     * @param index 索引
     */
    public void smoothTo(int index) {
        currentPageIndex = index;
        viewPager.setCurrentItem(index, false);
    }


    /**
     * 显示评测结果
     *
     * @param er {@link EvaluateResult}
     */
    public void showResult(EvaluateResult er) {
        SpeechTextView speechView = getCurrentSpeech();
        if (speechView == null) {
            Log.e("debug", "showResult speechView nnull");
            return;
        }
        Sentence sentence = speechView.getSentence();
        sentence = WordUtil.dealWordColoration(er, sentence);
        speechView.setSentence(sentence, scoreView, false);
        speechView.setTextColor(
                getResources().getColor(R.color.repeat_read_gray));
    }

    /**
     * 重置当前单词
     */
    public void resetCurrWord() {
        SpeechTextView currentSpeech = getCurrentSpeech();
        Sentence sentence = currentSpeech.getSentence();
        sentence.setHasGrade(false);
        currentSpeech.setSentence(sentence);
    }

    /**
     * 设置当前单词的颜色
     *
     * @param color 颜色值
     */
    public void setCurrentWordColor(int color) {
        SpeechTextView speechView = getCurrentSpeech();
        if (speechView == null) {
            return;
        }
        Sentence sentence = speechView.getSentence();
        for (WordDetail w : sentence.getWordDetails()) {
            w.setColor(color);
        }
        speechView.setSentence(sentence);
    }

    /**
     * 获取当前的SpeechTextView
     *
     * @return {@link SpeechTextView}
     */
    public SpeechTextView getCurrentSpeech() {
        return getSpeechTextView(viewPager.getCurrentItem());
    }

    private UnitSpeechView.UnitSpeechHolder getUnitSpeechHolder(int position) {
        View cur = viewPager.findViewWithTag(position);
        if (cur == null) {
            return null;
        }
        UnitSpeechView.UnitSpeechHolder holder = (UnitSpeechView.UnitSpeechHolder) cur
                .getTag(R.string.speech_tag_holder);
        return holder;
    }

    /**
     * 获取指定索引的 SpeechTextView
     *
     * @param position 指定索引
     * @return {@link SpeechTextView}
     */
    public SpeechTextView getSpeechTextView(int position) {
        UnitSpeechView.UnitSpeechHolder holder = getUnitSpeechHolder(position);
        return holder == null ? null : holder.speech;
    }

    public TextView getCurentSymbolTextView() {
        UnitSpeechView.UnitSpeechHolder holder = getUnitSpeechHolder(viewPager.getCurrentItem());
        return holder == null ? null : holder.symbol;
    }

    /**
     * 页码发生变化
     *
     * @param listener
     */
    public void setOnPageSelectChangeListener(
            UnitSpeechView.OnPageSelectChangeListener listener) {
        mSelelectChangeListener = listener;
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (mSelelectChangeListener != null) {
            mSelelectChangeListener.onPageSelected(position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    public class ViewPageAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return wordDatas == null ? 0 : wordDatas.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            CWLog.d("debug", "destroyItem:" + object);
            container.removeView((ScrollView) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            final UnitSpeechView.UnitSpeechHolder holder = new UnitSpeechView.UnitSpeechHolder();
            holder.spokenContainer = inflater.inflate(R.layout.unit_speech,
                    null);
            container.addView(holder.spokenContainer);
            holder.unitPic = (ImageView) holder.spokenContainer
                    .findViewById(R.id.unitPic);
            holder.speech = (SpeechTextView) holder.spokenContainer
                    .findViewById(R.id.speech);
            holder.symbol = (ColorationTextView) holder.spokenContainer
                    .findViewById(R.id.symbol);
            holder.pretations = (TextView) holder.spokenContainer
                    .findViewById(R.id.pretations);
            holder.sentences = (TextView) holder.spokenContainer
                    .findViewById(R.id.sentences);
            holder.spokenContainer.setTag(position);
            holder.spokenContainer.setTag(R.string.speech_tag_holder, holder);
            holder.vLine = holder.spokenContainer
                    .findViewById(R.id.view_line);
            holder.tvExampleSentence = (TextView) holder.spokenContainer
                    .findViewById(R.id.tv_example_sentence);
            Sentence sentence = wordDatas.get(position);
            WordDetail word = sentence.getWordDetails().get(0);
            String symbol = word.getSymbol();
            if (symbol != null) {
                if (!symbol.startsWith("[")) {
                    symbol = "[" + symbol;
                }
                if (!symbol.endsWith("]")) {
                    symbol += "]";
                }
                word.setSymbol(symbol);
            }
            holder.symbol.setText(word.getSymbol());
            holder.pretations.setText(word.getPretations());
            if (!TextUtils.isEmpty(word.getSentences())) {
                holder.tvExampleSentence.setVisibility(VISIBLE);
                holder.vLine.setVisibility(VISIBLE);
                String text = word.getSentences();
                String replaceTxt = text.replace("\r", "\n");
                holder.sentences.setText(replaceTxt);
            } else {
                holder.vLine.setVisibility(GONE);
                holder.tvExampleSentence.setVisibility(GONE);
            }

            holder.speech.setScoreColor(scoreDefColor);
            holder.speech.setSentence(sentence);
            ImageSize size = new ImageSize(DeviceUtils.getScreenWdith(),
                    R.dimen.word_pic_height);
            ImageLoader.getInstance().loadImage(
                    word.getWordPic(), size,
                    new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view,
                                                    FailReason failReason) {


                        }

                        @Override
                        public void onLoadingComplete(String s, View view,
                                                      Bitmap bitmap) {
                            holder.unitPic.setImageBitmap(bitmap);
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });

            return holder.spokenContainer;
        }

        @Override
        public boolean isViewFromObject(View view, Object arg1) {
            return view == arg1;
        }

    }

    public void setSymbolColoration(EvaluateResult eResult) {
        TextView curentSymbolTextView = getCurentSymbolTextView();
        if (curentSymbolTextView != null && curentSymbolTextView instanceof ColorationTextView) {
            ColorationTextView colorTextView = (ColorationTextView) curentSymbolTextView;
            colorTextView.setSymbolColoration(eResult, getCurrentOriginSysmbol());
        }
    }

    public String getCurrentOriginSysmbol() {
        try {
            if (wordDatas != null && wordDatas.size() > 0) {
                Sentence sentence = wordDatas.get(viewPager.getCurrentItem());
                WordDetail word = sentence.getWordDetails().get(0);
                String symbol = word.getSymbol();
                if (symbol != null) {
                    if (!symbol.startsWith("[")) {
                        symbol = "[" + symbol;
                    }
                    if (!symbol.endsWith("]")) {
                        symbol += "]";
                    }
                }
                return symbol;
            }
        } catch (Exception e) {
            return "[]";
        }
        return "[]";
    }


}
